import React, { useEffect, useState, useRef } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import {
    Button,
    Form,
    Input,
    Upload,
    message,
    Select,
    DatePicker,
    ConfigProvider,
    Radio,
    Row,
    Col,
    Progress
} from 'antd';
import locale from 'antd/locale/zh_CN';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import SparkMD5 from 'spark-md5';

axios.defaults.baseURL = 'http://localhost:3000/';
dayjs.locale('zh-cn');
const style = {
    display: 'flex',
    flexDirection: 'column',
    gap: 8,
};

const { Option } = Select;
// 定义文件分片大小（例如 5MB）
const CHUNK_SIZE = 5 * 1024 * 1024;

const Space = () => {
    const [tags, setTags] = useState([]);
    const [form] = Form.useForm();
    const [value, setValue] = useState(1);
    const navigate = useNavigate();
    const [publishDate, setPublishDate] = useState(dayjs());
    const [formData, setFormData] = useState({
        title: '',
        cover: [],
        sequence: null,
        tagIds: []
    });
    const [errorMessage, setErrorMessage] = useState('');
    const [file, setFile] = useState(null); // 用于存储用户选择的文件
    const [uploadProgress, setUploadProgress] = useState(0); // 上传进度
    const uploading = useRef(false); // 用于防止重复触发上传逻辑

    // 计算文件的唯一标识 (哈希)
    const calculateFileHash = async (file) => {
        // 调试输出文件对象信息
        console.log('传入 calculateFileHash 的文件对象:', file);
        if (!file || !(file instanceof File)) {
            throw new Error('传入的文件对象无效');
        }
        return new Promise((resolve) => {
            const reader = new FileReader();
            const hash = new SparkMD5.ArrayBuffer();

            reader.onload = (e) => {
                hash.append(e.target.result);
                resolve(hash.end());
            };

            reader.readAsArrayBuffer(file);
        });
    };

    const handleFileChang = async (info) => {
        console.log('handleFileChang 函数被调用，info:', info);
        const { fileList } = info;
        if (fileList.length === 0) {
            message.error('未选择文件');
            setUploadProgress(0); // 没有文件时重置进度
            return;
        }

        const selectedFile = fileList[0];
        console.log('selectedFile 完整对象:', selectedFile);

        if (selectedFile.status === 'uploading') {
            return;
        }

        if (selectedFile.status === 'removed') {
            console.log('文件已删除');
            setUploadProgress(0); // 文件删除时重置进度
            return;
        }

        if (selectedFile.status === 'done') {
            message.success(`${selectedFile.name} 文件上传成功`);
            return;
        }

        if (selectedFile.status === 'error') {
            message.error(`${selectedFile.name} 文件上传失败`);
            setUploadProgress(0); // 上传失败时重置进度
            return;
        }

        const originFile = selectedFile.originFileObj || selectedFile;
        if (!originFile || !(originFile instanceof File)) {
            message.error('未获取到有效的文件对象');
            console.error('未获取到有效的文件对象，selectedFile:', selectedFile);
            setUploadProgress(0); // 无有效文件时重置进度
            return;
        }

        setFile(originFile);
        setUploadProgress(0);

        if (uploading.current) return;
        uploading.current = true;

        try {
            const fileHash = await calculateFileHash(originFile);
            console.log('fileHash', fileHash);
            const totalChunks = Math.ceil(originFile.size / CHUNK_SIZE);

            const { data: uploadedChunks } = await axios.post(
                '/videos/check',
                {
                    fileName: originFile.name,
                    fileHash,
                },
            );

            for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
                if (uploadedChunks?.includes(chunkIndex)) {
                    console.log('跳过chunkIndx', chunkIndex);
                    setUploadProgress(((chunkIndex + 1) / totalChunks) * 100);
                    continue;
                }
                console.log('上传chunkIndx', chunkIndex);
                const start = chunkIndex * CHUNK_SIZE;
                const end = Math.min(originFile.size, start + CHUNK_SIZE);
                const chunk = originFile.slice(start, end);

                const formData = new FormData();
                formData.append('chunk', chunk);
                formData.append('fileName', originFile.name);
                formData.append('fileHash', fileHash);
                formData.append('chunkIndex', chunkIndex);

                const response = await axios.post(
                    `/videos/upload?fileHash=${fileHash}&chunkIndex=${chunkIndex}&fileName=${originFile.name}`,
                    formData,
                    {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        },
                        onUploadProgress: (progressEvent) => {
                            const progress =
                                ((chunkIndex + progressEvent.loaded / progressEvent.total) /
                                    totalChunks) *
                                100;
                            setUploadProgress(progress);
                        },
                    },
                );
                if (response.status!== 200) {
                    throw new Error(`分片 ${chunkIndex} 上传失败`);
                }
            }

            const mergeResponse = await axios.post('/videos/merge', {
                fileName: originFile.name,
                fileHash,
                totalChunks,
            });
            if (mergeResponse.status === 200) {
                message.success('视频上传成功！');
            } else {
                throw new Error('视频合并失败');
            }
        } catch (error) {
            message.error('视频上传失败，请稍后重试！');
            console.error('视频上传失败:', error);
            setUploadProgress(0); // 上传出错时重置进度
        } finally {
            uploading.current = false;
        }
    };

    const onChange = (date, dateString) => {
        if (value === 2) {
            setPublishDate(date);
        }
    };

    const getTags = async () => {
        try {
            const { data: { list } } = await axios.get('/kai/getbiao');
            setTags(list);
        } catch (error) {
            setErrorMessage('获取标签列表失败');
            console.error('获取标签列表失败', error);
        }
    };

    const onChanges = (e) => {
        setValue(e.target.value);
    };

    const handleInputChange = (e) => {
        const { name, value } = e.target;
        setFormData(prevData => ({
            ...prevData,
            [name]: value
        }));
    };

    const handleFileChange = (e, type) => {
        if (type === 'cover') {
            const file = e.file.originFileObj;
            const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
            if (file && allowedTypes.includes(file.type)) {
                setFormData(prevData => ({
                    ...prevData,
                    cover: [e.file]
                }));
            } else {
                message.error('请上传 JPEG、PNG 或 GIF 格式的图片');
            }
        }
    };

    const createCoverFormData = (file) => {
        const formData = new FormData();
        formData.append('file', file);
        return formData;
    };

    const handleSave = async () => {
        try {
            let coverUrl = '';
            if (formData.cover && formData.cover.length > 0) {
                const file = formData.cover[0].originFileObj;
                const formDataToSend = createCoverFormData(file);
                const uploadResponse = await axios.post('/kai/uploads', formDataToSend);
                coverUrl = uploadResponse.data.path;
            }

            const { title, tagIds } = formData;
            const currentDate = dayjs();
            let statusId;
            if (publishDate.isBefore(currentDate)) {
                statusId = '67b572653ea18c8e1bfad415';
            } else {
                statusId = '67b5721a3ea18c8e1bfad413';
            }

            const dataToSend = {
                ren: '李子凯',
                name: title,
                zid: statusId,
                cover: coverUrl,
                bid: tagIds,
                publishTime: publishDate.toDate()
            };

            const response = await axios.post('/kai/addvideo', dataToSend, {
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            console.log('添加视频信息接口响应状态码:', response.status);
            if (response.status === 200) {
                message.success('数据添加成功');
                navigate(-1);
            } else {
                setErrorMessage('数据添加失败');
            }
        } catch (error) {
            setErrorMessage('数据添加失败');
            console.error('数据添加失败', error);
        }
    };

    useEffect(() => {
        getTags();
    }, []);

    const uploadContainerStyle = {
        width: '100%',
        height: '100%',
        padding: '20px',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        border: '1px dashed #d9d9d9',
        borderRadius: '4px',
        transition: 'border-color 0.3s',
        backgroundColor: '#fafafa',
        boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)',
    };

    const uploadContainerHoverStyle = {
        borderColor: '#40a9ff',
        backgroundColor: '#e6f7ff',
    };

    return (
        <div
            style={{
                scrollbarWidth: 'none',
                overflowY: 'auto',
                margin: 'auto',
                width: '70%',
                height: '100%',
            }}
        >
            <div
                style={{
                    marginTop: '0.6rem',
                    overflow: 'hidden',
                    backgroundColor: 'white',
                    width: '100%',
                    height: '75%',
                    borderRadius: '20px',
                }}
            >
                <div style={{ display: 'flex', margin: '0.6rem' }}>
                    <div
                        style={{
                            width: '0.16rem',
                            marginTop: '0.02rem',
                            borderRadius: '0.1rem',
                            height: '0.8rem',
                            backgroundColor: '#3dd4a7',
                        }}
                    ></div>
                    <div style={{ fontSize: '0.5rem', marginLeft: '0.2rem' }}>新增视频</div>
                </div>
                <div>
                    <Form
                        labelCol={{
                            span: 4,
                        }}
                        wrapperCol={{
                            span: 14,
                        }}
                        layout="horizontal"
                        style={{
                            maxWidth: 600,
                        }}
                    >
                        <Form.Item label="视频名称">
                            <Input
                                name="title"
                                value={formData.title}
                                onChange={handleInputChange}
                            />
                        </Form.Item>

                        <Form.Item label="视频封面">
                            <Upload
                                listType="picture-card"
                                onChange={(e) => handleFileChange(e, 'cover')}
                                fileList={formData.cover}
                                accept="image/jpeg, image/png, image/gif"
                            >
                                <button
                                    style={{
                                        border: 0,
                                        background: 'none',
                                    }}
                                    type="button"
                                >
                                    <PlusOutlined />
                                    <div
                                        style={{
                                            marginTop: 8,
                                        }}
                                    >
                                        Upload
                                    </div>
                                </button>
                            </Upload>
                        </Form.Item>
                        <Form.Item label="视频">
                            <Upload
                                listType="picture-card"
                                onChange={handleFileChang}
                                beforeUpload={() => false} // 阻止默认上传行为
                            >
                                <div
                                    style={{
                                        ...uploadContainerStyle,
                                        ...(uploadProgress > 0 && {
                                            borderColor: '#52c41a',
                                            backgroundColor: '#f6ffed',
                                        }),
                                    }}
                                    onMouseEnter={(e) => {
                                        e.currentTarget.style = {
                                            ...uploadContainerStyle,
                                            ...uploadContainerHoverStyle,
                                        };
                                    }}
                                    onMouseLeave={(e) => {
                                        e.currentTarget.style = {
                                            ...uploadContainerStyle,
                                            ...(uploadProgress > 0 && {
                                                borderColor: '#52c41a',
                                                backgroundColor: '#f6ffed',
                                            }),
                                        };
                                    }}
                                >
                                    {uploadProgress === 0 && (
                                        <>
                                            <PlusOutlined style={{ fontSize: 24, color: '#999' }} />
                                            <div style={{ marginTop: 8, color: '#999' }}>上传视频</div>
                                        </>
                                    )}
                                    {uploadProgress > 0 && (
                                        <>
                                            <div style={{ marginTop: 8, color: '#52c41a' }}>
                                                上传进度: {uploadProgress.toFixed(2)}%
                                            </div>
                                            <Progress percent={uploadProgress} style={{ width: '100%', marginTop: 8 }} />
                                        </>
                                    )}
                                </div>
                            </Upload>
                        </Form.Item>
                        <Form.Item label="视频标签" name="tagIds">
                            <Select
                                mode="multiple"
                                placeholder="请选择视频标签"
                                style={{ width: '100%' }}
                                onChange={(value) => setFormData(prevData => ({
                                    ...prevData,
                                    tagIds: value
                                }))}
                            >
                                {tags.map((tag) => (
                                    <Option key={tag._id} value={tag._id}>
                                        {tag.name}
                                    </Option>
                                ))}
                            </Select>
                        </Form.Item>
                        <Form.Item label="发布时间">
                            <Row align="middle" gutter={16}>
                                <Col span={12}>
                                    <Radio.Group
                                        style={style}
                                        onChange={onChanges}
                                        value={value}
                                        options={[
                                            {
                                                value: 1,
                                                label: '立即发布',
                                            },
                                            {
                                                value: 2,
                                                label: '定时发布',
                                            },
                                        ]}
                                    />
                                </Col>
                                <Col span={12}>
                                    {value === 2 && (
                                        <ConfigProvider locale={locale}>
                                            <DatePicker
                                                onChange={onChange}
                                                style={{ width: '6rem', height: '1rem' }}
                                            />
                                        </ConfigProvider>
                                    )}
                                </Col>
                            </Row>
                        </Form.Item>
                        {errorMessage && (
                            <Form.Item wrapperCol={{ offset: 4, span: 14 }}>
                                <div style={{ color: 'red' }}>{errorMessage}</div>
                            </Form.Item>
                        )}
                        <Form.Item wrapperCol={{ offset: 4, span: 14 }}>
                            <Button
                                style={{ background: '#5adbb5', width: '2rem', height: '1rem' }}
                                type="primary"
                                onClick={handleSave}
                            >
                                保存
                            </Button>
                            <Button
                                style={{ marginLeft: '1rem', width: '2rem', height: '1rem' }}
                                onClick={() => {
                                    navigate(-1);
                                }}
                            >
                                返回
                            </Button>
                        </Form.Item>
                    </Form>
                </div>
            </div>
        </div>
    );
};

export default Space;